package com.polaris.live.dialog

import android.content.Context
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.DialogVipRenewalTipsBinding
import com.polaris.live.net.userService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.UserPartyBackgroundVipVo
import com.polaris.live.resp.go_resp.VipBuyRequest
import com.polaris.live.translation.R.string

/**
 * VipRenewalTipsDialog
 *
 * @author Created by 半仙 on 2024/12/20/020 10:31
 */
class VipRenewalTipsDialog(
    context: Context,
    private val vip: UserPartyBackgroundVipVo,
    private val viewModel: BaseViewModel,
    private val buyVipSuccess: () -> Unit,
) : CenterPopupView(context) {

    override fun getImplLayoutId() = R.layout.dialog_vip_renewal_tips

    private lateinit var mBinding: DialogVipRenewalTipsBinding

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogVipRenewalTipsBinding.bind(popupImplView)
        mBinding.apply {
            tvVipLevel.text = StringUtils.getString(string.you_now_vip_level, "VIP${vip.level}")
            tvVipTime.text = StringUtils.getString(string.you_vip_level_have, "${vip.days}")
            tvNeedMoney.text = vip.renewalPrice.toString()
            tvGetDay.text = "${vip.priceDays}day"
        }
        initListener()
    }

    private fun initListener() {
        mBinding.ivClose.setOnSingleClickListener {
            dismiss()
        }
        mBinding.llRenew.setOnSingleClickListener {
            viewModel.request({ userService.vipBuy(VipBuyRequest(vipLevel = vip.level)) }, {
                buyVipSuccess.invoke()
                dismiss()
            }, {
                when (it.errCode) {
                    CommonConst.ErrorCode.SENDGIFT -> {
                        GlobalPopupManager.showRechargePopup(
                            context,
                            viewModel,
                            isNeedBottom = true
                        )
                    }
                }
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    companion object {

        fun show(context: Context, vip: UserPartyBackgroundVipVo, viewModel: BaseViewModel, buyVipSuccess: () -> Unit) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(VipRenewalTipsDialog(context, vip, viewModel, buyVipSuccess))
                .show()
        }
    }

}